<template>
  <p-modal v-drag
    :width="modalWidth"
    :visible="visible"
    :title="title"
    @ok="handleSubmit"
    @cancel="close"
    cancelText="关闭"
    style="margin-top: -70px"
    wrapClassName="ant-modal-cust-warp"
  >
    <p-row :gutter="10" style="background-color: #ececec; padding: 10px; margin: -10px">
      <p-col :md="24" :sm="24">
        <p-card :bordered="false">
          搜索:
          <p-input-search
            :style="{width:'150px',marginBottom:'15px'}"
            placeholder="请输入关键字"
            v-model="queryParam.keyword"
            @input="onSearch"
          ></p-input-search>
          <p-button @click="searchReset(1)" style="margin-left: 20px" icon="redo">重置</p-button>
          <!--用户列表-->
          <p-table
            ref="table"
            :scroll="scrollTrigger"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: getType}"
            @change="handleTableChange"
            :customRow="clickThenSelect">
          </p-table>
        </p-card>
      </p-col>
    </p-row>
  </p-modal>
</template>

<script>
  import { filterObj } from '@/utils/util'
  import {
  postAction,
  getAction,
  deleteAction,
  putAction,
  api,
} from "@/api/manage";

  export default {
    name: 'JSelectUserByDepModal',
    components: {},
    props: ['modalWidth', 'multi', 'userIds',"ObjectList"],
    data () {
      return {
        queryParam: {
          username: '',
        },
        columns: [
          {
            title: '工号',
            align: 'center',
            dataIndex: 'empno'
          },
          {
            title: '用户姓名',
            align: 'center',
            dataIndex: 'empname'
          },
          {
            title: '性别',
            align: 'center',
            dataIndex: 'empsex',
            customRender: function (text) {
                if (text === '1') {
                return '男'
              } else if (text === '2') {
                return '女'
              } else {
                return text
              }
            }
          },
          {
            title: '手机',
            align: 'center',
            dataIndex: 'mobilePhone'
          },
          {
            title: '部门',
            align: 'center',
            dataIndex: 'duty',// orgPosDtos.orgName
            customRender:function(t){
              if(t==1){return '厂长'}
              if(t==2){return '车间主任'}
              if(t==3){return '线长'}
              if(t==4){return '班长'}
              if(t==5){return '员工'}
              if(t==6){return '生管'}
            }
          }
        ],
        geiDataList:{},
        scrollTrigger: {},
        dataSource: [],
        selectedRowKeys: [],
        selectUserRows: [],
        selectUserIds: [],
        title: '根据部门选择用户',
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        selectedDepIds: [],
        replaceFields: { title: 'name', key: 'code' },
        departTree: [],
        visible: false,
        form: this.$form.createForm(this),
        loading: false,
        expandedKeys: [],
        url:{
          list:'/mes-manpower/mesHrEmployeeinfo/list'
        }
      }
    },
    computed: {
      // 计算属性的 getter
      getType: function () {
        return this.multi == true ? 'checkbox' : 'radio'
      }
    },
    watch: {
      userIds: {
        immediate: true,
        handler (val, oldval) {
          if (val != undefined) {
            this.selectedRowKeys = val.split(',')
          }
        },
        deep: true
      }
    },
    created () {
      this.loadData()
    },
    methods: {
      onLoadData(treeNode) {
        return new Promise(resolve => {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
        });
            
      },
      async loadData (arg) {
        const arr = [] // 用来定义存放新的数组
        if (arg === 1) {
          this.ipagination.current = 1
        }
        if (this.selectedDepIds && this.selectedDepIds.length > 0) {
          await this.initQueryUserByDepId(this.selectedDepIds)
        } else {
          this.loading = true
          const params = this.getQueryParams()// 查询条件
          await getAction(this.url.list,params).then((res) => {
            if (res.data.records.length > 0) {
              res.data.records.forEach((item, index) => {
                if (item.orgPosDtos) {
                  item['orgName'] = item.orgPosDtos[0].orgName
                  arr.push(item)
                } else {
                  arr.push(item)
                }
              })
              this.dataSource = arr
              this.ipagination.total = res.data.total
            }
          }).finally(() => {
            this.loading = false
          })
        }
      },
      showModal () {
        this.visible = true
        this.loadData()
        this.form.resetFields()
      },
      getQueryParams () {
        const param = Object.assign({}, this.queryParam, this.isorter)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField () {
        let str = 'id,'
        for (let a = 0; a < this.columns.length; a++) {
          str += ',' + this.columns[a].dataIndex
        }
        return str
      },
      searchReset (num) {
        const that = this
        if (num !== 0) {
          that.queryParam = {}
          that.loadData(1)
        }
        that.selectedRowKeys = []
        that.selectUserIds = []
        that.selectedDepIds = []
      },
      close () {
        this.searchReset(0)
        this.visible = false
      },
      handleTableChange (pagination, filters, sorter) {
        // TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc'
        }
        console.log(this.ipagination)
        this.ipagination = pagination
        this.loadData()
      },
      handleSubmit () {
        const that = this
        this.getSelectUserRows()
        that.$emit('ok', that.geiDataList)
        that.searchReset(0)
        that.close()
      },
      // 获取选择用户信息
      getSelectUserRows (rowId) {
        const dataSource = this.dataSource
        let userIds = ''
        this.selectUserRows = []
        for (let i = 0, len = dataSource.length; i < len; i++) {
          if (this.selectedRowKeys.includes(dataSource[i].uid)) {
            this.selectUserRows.push(dataSource[i])
            userIds = userIds + ',' + dataSource[i].uid
          }
        }
        this.selectUserIds = this.selectedRowKeys
      },
      clickThenSelect(record) {
      return {
        on: {
          click: () => {
            this.$emit('ok', record)
            this.searchReset(0)
            this.close()
          },
        },
      };
    },
      // 点击树节点,筛选出对应的用户
      onDepSelect (selectedDepIds) {
        if (selectedDepIds[0] != null) {
          this.initQueryUserByDepId(selectedDepIds) // 调用方法根据选选择的id查询用户信息
          if (this.selectedDepIds[0] !== selectedDepIds[0]) {
            this.selectedDepIds = [selectedDepIds[0]]
          }
        }
      },
      onSelectChange (selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
        this.geiDataList=this.selectionRows[0]
      },
      onSearch () {
        this.loadData(1)
      },

      // 根据选择的code来查询用户信息
      initQueryUserByDepId (selectedDepIds) {
        this.loading = true
        const arr = []
        return getUserList({ orgCode: selectedDepIds.toString(',') }).then((res) => {
          if (res.success) {
            if (res.data.total !== 0) {
              res.data.records.forEach((item, index) => {
                if (item.orgPosDtos) {
                  item['orgName'] = item.orgPosDtos[0].orgName
                  arr.push(item)
                } else {
                  arr.push(item)
                }
              })
              this.dataSource = arr
              this.ipagination.total = res.data.total
            } else {
              this.dataSource = []
              this.ipagination.total = 0
            }
          }
        }).finally(() => {
          this.loading = false
        })
      },
      modalFormOk () {
        this.loadData()
      }
    }
  }
</script>

<style scoped>
  .poros-table-tbody .poros-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  #components-layout-demo-custom-trigger .trigger {
    font-size: 18px;
    line-height: 64px;
    padding: 0 24px;
    cursor: pointer;
    transition: color .3s;
  }
</style>
